import { DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Col, Form, Row, Select, Upload, message } from 'antd';
import { useEffect, useState } from 'react';
import { allTenantList } from '@/services/ant-design-pro/tenantSet'
const UploadFile = (props) => {
  let [fileList, setFileList] = useState([]);
  let [tenantOptions, setTenantOptions] = useState([]); //租户选项数组

  //钩子函数
  useEffect(() => {
    getTenantOptions();
  }, []); // 空数组表示只在组件加载时执行一次

  //获取租户选项数组
  const getTenantOptions = async () => {
    await allTenantList()
      .then((result) => {  
        //后端传过来的数组
        if (result.success) {
          if (result.data) {
            let options = [];
            result.data.forEach((e) => {
              let { tenantId, tenantName } = e;
              let option = {
                value: tenantId,
                label: tenantName,
              };
              options.push(option);
            });
            setTenantOptions(options);
          }
        }
      });
  };
  //上传参数
  const upload_props = {
    //删除
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    //上传前事件
    beforeUpload: (file) => {
      if (file.name.endsWith('.xlsx')) {
        setFileList([file]);
      } else {
        message.error('请上传xlsx文件！');
      }

      return false;
    },
    fileList,
    accept: '.xlsx',
  };

  //表单 提交事件
  const onFinish = (values) => {
    console.log(values);
    //校验上传的是否为xlsx文件
    let xlsxFile = fileList.find((e) => {
      let fileName = e.name;
      const fileExtension = fileName.substring(fileName.lastIndexOf('.'));
      if (fileExtension == '.xlsx') {
        return true;
      } else {
        return false;
      }
    });

    if (!xlsxFile) {
      message.error('请上传.xlsx 文件！');
      return;
    }

    //上传的文件
    let formData = new FormData();
    formData.append('file', fileList[0]);
    formData.append('tenantId', values.tenantId);

    //ajax
    fetch(API_URL + '/importTable/upload', {
      method: 'POST',
      body: formData,
    })
      .then((res) => res.json())
      .then((e) => {
        let { success } = e;
        if (success) {
          let { filePath, tenantId, excelFileName } = e;
          let uploadInfo = {
            filePath,
            tenantId,
            excelFileName,
          };
          props.setUploadInfo(uploadInfo);
          props.setUploaded(true);
          setFileList([]);
          message.success('上传成功');
        } else {
          message.error(e.message);
        }
      });
  };
  //表单 提交失败事件
  const onFinishFailed = (errorInfo) => {
    console.log(errorInfo);
  };

  const getTemplate = () => {
    // 发送文件名给后端并下载文件
    fetch(API_URL + '/importTable/getTemplate', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('请求失败');
        }
        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = '协同表单模板.xlsx'; // 下载文件的名称
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      })
      .catch((error) => console.error('文件下载失败:', error));
  };
  return (
    <div>
      <Row justify="center" align="middle" style={{ height: '50vh' }}>
        <Col>
          <Form
            name="basic"
            labelCol={{ span: 10, offset: 0 }}
            wrapperCol={{ span: 80, offset: 0 }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
            layout="horizontal"
            colon={true} //显示逗号
          >
            <Form.Item name="getTemplate">
              <Button type="default" onClick={getTemplate}>
                <DownloadOutlined />
                模板下载
              </Button>
            </Form.Item>

            <Form.Item
              label="租户名称"
              name="tenantId"
              rules={[
                {
                  required: true,
                  message: '请选择租户!',
                },
              ]}
            >
              <Select options={tenantOptions} />
            </Form.Item>
            <Form.Item
              label="excel文件"
              name="excel"
              rules={[
                {
                  required: true,
                  message: '请上传文件!',
                },
              ]}
            >
              <Upload {...upload_props}>
                <Button icon={<UploadOutlined />}>上传</Button>
              </Upload>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
    </div>
  );
};
export default UploadFile;
